<template>
  <!-- 产品物料管理页面主容器 -->
  <div class="product-materials-container">
    <!-- 顶部操作区域：包含搜索、新增、导入导出等功能按钮 -->
    <div class="top-section">
      <!-- 搜索区域动画过渡效果 -->
      <transition name="search-slide">
        <!-- 搜索条件输入区域 -->
        <div class="search-area" v-show="showSearchArea">
          <!-- 当前搜索条件状态显示 -->
          <div class="search-status" v-if="hasSearchConditions">
            <el-tag size="small" type="info">
              当前搜索条件: {{ getSearchConditionsText() }}
            </el-tag>
            <el-tag size="small" type="success" style="margin-left: 10px;">
              找到 {{ total }} 条结果
            </el-tag>
          </div>
          <!-- 搜索输入框和按钮区域 -->
          <div class="search-controls">
            <el-input v-model="searchForm.materialsCode" placeholder="请输入产品物料编码" class="search-input" clearable
              @keyup.enter="handleSearch" />
            <el-input v-model="searchForm.materialsName" placeholder="请输入产品物料名称" class="search-input" clearable
              @keyup.enter="handleSearch" />
            <el-input v-model="searchForm.materialsMsg" placeholder="请输入产品物料描述" class="search-input" clearable
              @keyup.enter="handleSearch" />
            <el-input v-model="searchForm.spec" placeholder="请输入产品物料规格" class="search-input" clearable
              @keyup.enter="handleSearch" />
            <el-select v-model="searchForm.itemTypeId" placeholder="请选择物料类型" class="search-input" clearable
              @change="handleSearch">
              <el-option v-for="item in groupTypes" :key="item.id" :label="item.groupTypeName" :value="item.id" />
            </el-select>
            <el-input v-model="searchForm.itemName" placeholder="请输入群组名称" class="search-input" clearable
              @keyup.enter="handleSearch" />
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </el-button>
            <el-button @click="clearSearch" class="clear-btn">
              <el-icon>
                <Close />
              </el-icon>
              清空
            </el-button>
            <el-dropdown @command="loadSearchHistory" v-if="searchHistory.length > 0">
              <el-button class="history-btn">
                <el-icon>
                  <Clock />
                </el-icon>
                历史
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="(item, index) in searchHistory" :key="index" :command="item">
                    {{ getSearchHistoryText(item) }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </transition>
      <!-- 工具图标区域：搜索切换、刷新、全屏、设置等辅助功能 -->
      <div class="utility-icons">
        <!-- 搜索区域显示/隐藏切换按钮 -->
        <el-tooltip :content="showSearchArea ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-icon class="icon-btn" @click="toggleSearchArea" :class="{ 'active': showSearchArea }">
            <Search />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="刷新" placement="top">
          <el-icon class="icon-btn" @click="refreshData">
            <Refresh />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="全屏" placement="top">
          <el-icon class="icon-btn" @click="toggleFullscreen">
            <Expand />
          </el-icon>
        </el-tooltip>      
      </div>
    </div>

    <!-- 操作按钮区域：新增、导出、导入、删除等主要功能 -->
    <div class="action-section">
      <div class="action-buttons">
        <!-- 新增产品物料按钮 -->
        <el-button type="primary" @click="handleAdd" class="action-btn">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button type="primary" @click="handleExport" class="action-btn">
          <el-icon>
            <Download />
          </el-icon>
          导出
        </el-button>
        <el-button type="success" @click="handleImport" class="action-btn">
          <el-icon>
            <Upload />
          </el-icon>
          导入
        </el-button>
        <el-button @click="handleBatchDelete" class="action-btn delete-btn">
          <el-icon>
            <Delete />
          </el-icon>
          删除
        </el-button>
      </div>
    </div>

    <!-- 数据表格区域：显示产品物料列表 -->
    <div class="table-section">
      <!-- 产品物料数据表格 -->
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" class="data-table"
        border stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="80" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="materialsCode" label="物料编码" width="150" align="center">
          <template #header>
            <span>物料编码</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="materialsName" label="物料名称" width="200" align="center">
          <template #header>
            <span>物料名称</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="itemTypeName" label="物料类型" width="150" align="center">
          <template #header>
            <span>物料类型</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.itemTypeId)" size="small">
              {{ scope.row.itemTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="itemGroupName" label="所属群组" width="150" align="center">
          <template #header>
            <span>所属群组</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="单位" width="100" align="center" />
        <el-table-column prop="spec" label="规格" width="150" align="center" />
        <el-table-column prop="warnQty" label="预警数量" width="100" align="center" />
        <el-table-column prop="routingName" label="工艺路线" width="180" align="center">
          <template #header>
            <span>工艺路线</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="materialsMsg" label="描述" min-width="150" align="center" />
        <el-table-column prop="addProp" label="创建人" width="120" align="center" />
        <el-table-column prop="addTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ moment(scope.row.addTime).format("yyyy-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="updTime" label="更新时间" width="160" align="center">
          <template #default="scope">
            {{ moment(scope.row.updTime).format("yyyy-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)" class="action-link">
              编辑
            </el-button>
            <el-button type="text" @click="handleDelete(scope.row)" class="action-link delete-link">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域：数据分页控制和统计信息 -->
    <div class="pagination-section">
      <div class="data-summary">
        共{{ total }}条数据
      </div>
      <div class="pagination-controls">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 新增/编辑对话框：产品物料的添加和修改表单 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="resetForm"
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="true" :close-icon="Close">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="material-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编码" prop="materialsCode" required>
              <el-input v-model="form.materialsCode" placeholder="请输入物料编码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="materialsName" required>
              <el-input v-model="form.materialsName" placeholder="请输入物料名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input v-model="form.spec" placeholder="请输入规格型号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit" required>
              <el-select v-model="form.unit" placeholder="请选择单位" style="width: 100%" clearable>
                <el-option v-for="item in units" :key="item.id" :label="item.unitName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预警值" prop="warnQty">
              <div style="display: flex; align-items: center; width: 100%;">
                <el-input-number v-model="form.warnQty" :min="0" placeholder="请输入预警值" />
                <el-icon class="info-icon" style="margin-left: 8px;">
                  <InfoFilled />
                </el-icon>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="群组类型" prop="itemTypeId" required>
              <el-select v-model="form.itemTypeId" placeholder="请选择群组类型" style="width: 100%"
                @change="handleItemTypeChange" clearable>
                <el-option v-for="item in groupTypes" :key="item.id" :label="item.groupTypeName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="群组" prop="itemName" required>
              <el-select v-model="form.itemName" placeholder="请选择群组" style="width: 100%" @change="handleItemGroupChange"
                clearable>
                <el-option v-for="item in itemGroups" :key="item.id" :label="item.itemName" :value="item.itemName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showProcessRoute">
            <el-form-item label="工艺路线" prop="routingId" required>
              <el-select v-model="form.routingId" placeholder="请选择工艺路线" style="width: 100%" clearable>
                <el-option v-for="route in processRoutes" :key="route.id" :label="route.routingName" :value="route.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="materialsMsg">
          <el-input v-model="form.materialsMsg" type="textarea" :rows="3" placeholder="请输入描述" resize="both"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 产品物料管理页面
 * 功能：产品物料的增删改查、导入导出、搜索筛选等
 * 作者：系统
 * 创建时间：2024年
 */

import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import {
  Plus,
  Download,
  Delete,
  Grid,
  Search,
  Refresh,
  Expand,
  Setting,
  Close,
  Sort,
  Clock,
  ArrowDown,
  InfoFilled,
  Upload
} from '@element-plus/icons-vue'
import Maxios from '@/Http/MesHelp'

// ==================== 接口定义 ====================
/**
 * 产品物料数据接口
 */
interface ProductMaterial {
  id: number
  materialsCode: string
  materialsName: string
  materialsMsg: string
  spec: string
  unit: number
  unitName: string
  warnQty: number
  itemTypeId: number
  itemTypeName: string
  itemGroupId: number
  itemGroupName: string
  routingId: number
  routingName: string
  addProp: string
  addTime: string
  updProp?: string
  updTime?: string
}

/**
 * 群组类型数据接口
 */
interface GroupType {
  id: number
  groupTypeName: string
}

/**
 * 物料群组数据接口
 */
interface ItemGroup {
  id: number
  itemName: string
}

/**
 * 单位数据接口
 */
interface Unit {
  id: number
  unitName: string
}

/**
 * 工艺路线数据接口
 */
interface ProcessRoute {
  id: number
  routingName: string
}

// ==================== 响应式数据定义 ====================
/**
 * 页面状态管理
 */
const loading = ref(false) // 表格加载状态
const tableData = ref<ProductMaterial[]>([]) // 表格数据
const selectedRows = ref<ProductMaterial[]>([]) // 选中的行数据
const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示数量
const total = ref(0) // 总数据量
const dialogVisible = ref(false) // 对话框显示状态
const dialogTitle = ref('新增产品物料') // 对话框标题
const isEdit = ref(false) // 是否为编辑模式
const groupTypes = ref<GroupType[]>([]) // 群组类型数据
const itemGroups = ref<ItemGroup[]>([]) // 物料群组数据
const units = ref<Unit[]>([]) // 单位数据
const processRoutes = ref<ProcessRoute[]>([]) // 工艺路线数据
const showSearchArea = ref(false) // 搜索区域显示状态
const searchHistory = ref<Array<{ materialsCode: string, materialsName: string, materialsMsg: string, spec: string, itemTypeId: number | null, itemName: string }>>([]) // 搜索历史记录

/**
 * 导入导出功能相关状态
 * 注意：已移除导入对话框，改为直接文件选择方式
 */
// 导入导出相关
// 移除导入对话框相关状态变量

// ==================== 表单数据定义 ====================
/**
 * 搜索表单数据：用于条件筛选产品物料
 */
const searchForm = reactive({
  materialsCode: '', // 物料编码搜索条件
  materialsName: '', // 物料名称搜索条件
  materialsMsg: '', // 物料描述搜索条件
  spec: '', // 物料规格搜索条件
  itemTypeId: null as number | null, // 物料类型搜索条件
  itemName: '' // 群组名称搜索条件
})

/**
 * 新增/编辑表单数据：用于添加和修改产品物料信息
 */
const formRef = ref() // 表单引用
const form = reactive({
  id: 0, // 物料ID
  materialsCode: '', // 物料编码
  materialsName: '', // 物料名称
  materialsMsg: '', // 物料描述
  spec: '', // 物料规格
  unit: null as number | null, // 计量单位ID
  warnQty: 0, // 预警数量
  itemTypeId: null as number | null, // 物料类型ID
  itemName: '', // 所属群组名称
  routingId: null as number | null, // 工艺路线ID
  addProp: localStorage.getItem("userNickname") || '' // 创建人
})

/**
 * 表单验证规则：确保数据的完整性和正确性
 */
const rules = {
  materialsCode: [
    { required: true, message: '请输入编码', trigger: 'blur' }
  ],
  materialsName: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  itemTypeId: [
    { required: true, message: '请选择群组类型', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  itemName: [
    { required: true, message: '请选择群组', trigger: 'change' }
  ],
  routingId: [
    {
      required: true,
      message: '请选择工艺路线',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (showProcessRoute.value && !value) {
          callback(new Error('请选择工艺路线'))
        } else {
          callback()
        }
      }
    }
  ]
}

// ==================== API接口方法 ====================
/**
 * API基础配置
 */
const API_BASE_URL = '/api'

/**
 * 获取群组类型数据
 * 用于物料类型下拉选择
 */
const getGroupTypes = async () => {
  try {
    const response = await Maxios.post(`${API_BASE_URL}/Band/GroupTypeGet`)
    if (response.data.code === 200) {
      groupTypes.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取群组类型失败')
    }
  } catch (error) {
    console.error('获取群组类型失败:', error)
    // 如果API调用失败，使用模拟数据
    groupTypes.value = [
      { id: 1, groupTypeName: '原材料' },
      { id: 2, groupTypeName: '半成品' },
      { id: 3, groupTypeName: '成品' },
      { id: 4, groupTypeName: '上工件' }
    ]
  }
}

/**
 * 获取物料群组数据
 * 用于群组下拉选择
 */
const getItemGroups = async () => {
  try {
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/ItemGroupQuery`, {
      ItemCode: null,
      ItemName: null,
      ItemMsg: null,
      ItemTypeId: null,
      PageIndex: 1,
      PageSize: 1000
    })
    if (response.data.code === 200) {
      itemGroups.value = response.data.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取物料群组失败')
    }
  } catch (error) {
    console.error('获取物料群组失败:', error)
    // 使用模拟数据
    itemGroups.value = [
      { id: 1, itemName: '原材料A' },
      { id: 2, itemName: '成品B' },
      { id: 3, itemName: '半成品C' }
    ]
  }
}

/**
 * 获取单位数据
 * 用于计量单位下拉选择
 */
const getUnits = async () => {
  try {
    const response = await Maxios.post(`${API_BASE_URL}/Band/UnitGet`)
    if (response.data.code === 200) {
      units.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取单位失败')
    }
  } catch (error) {
    console.error('获取单位失败:', error)
    // 使用模拟数据
    units.value = [
      { id: 1, unitName: '个' },
      { id: 2, unitName: '件' },
      { id: 3, unitName: '套' },
      { id: 4, unitName: '米' }
    ]
  }
}

/**
 * 获取工艺路线数据
 * 用于成品和半成品的工艺路线选择
 */
const getProcessRoutes = async () => {
  try {
    const response = await Maxios.get(`${API_BASE_URL}/Process/GetProccessRouting`)
    if (response.data.code === 200) {
      processRoutes.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取工艺路线失败')
    }
  } catch (error) {
    console.error('获取工艺路线失败:', error)
    ElMessage.error('获取工艺路线失败')
  }
}

/**
 * 获取产品物料列表数据
 * 支持分页和条件筛选
 */
const getProductMaterials = async () => {
  loading.value = true
  try {
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsQuery`, {
      MaterialsCode: searchForm.materialsCode || null,
      MaterialsName: searchForm.materialsName || null,
      MaterialsMsg: searchForm.materialsMsg || null,
      Spec: searchForm.spec || null,
      Unit: null,
      ItemTypeId: searchForm.itemTypeId,
      ItemName: searchForm.itemName || null,
      PageIndex: currentPage.value,
      PageSize: pageSize.value
    })

    if (response.data.code === 200) {
      const result = response.data.data
      tableData.value = result.data || []
      total.value = result.total || 0
      currentPage.value = result.pageIndex || 1
      pageSize.value = result.pageSize || 10
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取产品物料失败:', error)
    // 使用模拟数据
    const mockData: ProductMaterial[] = [
      {
        id: 1,
        materialsCode: 'PM001',
        materialsName: '产品物料A',
        materialsMsg: '用于生产的主要产品物料',
        spec: '规格A',
        unit: 1,
        unitName: '个',
        warnQty: 100,
        itemTypeId: 2,
        itemTypeName: '成品',
        itemGroupId: 2,
        itemGroupName: '成品B',
        routingId: 1,
        routingName: '冲压线-钢盖',
        addProp: '(test)管理员',
        addTime: '2024-01-15 10:30:00',
        updTime: ''
      },
      {
        id: 2,
        materialsCode: 'PM002',
        materialsName: '产品物料B',
        materialsMsg: '半成品物料',
        spec: '规格B',
        unit: 2,
        unitName: '件',
        warnQty: 50,
        itemTypeId: 4,
        itemTypeName: '半成品',
        itemGroupId: 3,
        itemGroupName: '半成品C',
        routingId: 2,
        routingName: '组焊',
        addProp: '(test)管理员',
        addTime: '2024-01-16 14:20:00',
        updTime: ''
      }
    ]

    // 过滤数据
    let filteredData = mockData
    if (searchForm.materialsCode) {
      filteredData = filteredData.filter(item =>
        item.materialsCode.toLowerCase().includes(searchForm.materialsCode.toLowerCase())
      )
    }
    if (searchForm.materialsName) {
      filteredData = filteredData.filter(item =>
        item.materialsName.toLowerCase().includes(searchForm.materialsName.toLowerCase())
      )
    }
    if (searchForm.materialsMsg) {
      filteredData = filteredData.filter(item =>
        item.materialsMsg.toLowerCase().includes(searchForm.materialsMsg.toLowerCase())
      )
    }
    if (searchForm.spec) {
      filteredData = filteredData.filter(item =>
        item.spec.toLowerCase().includes(searchForm.spec.toLowerCase())
      )
    }
    if (searchForm.itemTypeId) {
      filteredData = filteredData.filter(item => item.itemTypeId === searchForm.itemTypeId)
    }
    if (searchForm.itemName) {
      filteredData = filteredData.filter(item =>
        item.itemGroupName.toLowerCase().includes(searchForm.itemName.toLowerCase())
      )
    }

    total.value = filteredData.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = filteredData.slice(start, end)
  } finally {
    loading.value = false
  }
}

// ==================== 业务逻辑方法 ====================
/**
 * 根据类型ID获取对应的标签样式类型
 * 用于物料类型的颜色标识
 */
const getTagType = (typeId: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'danger',    // 原材料
    2: 'primary',   // 成品
    3: 'success',   // 上工件
    4: 'info'       // 半成品
  }
  return typeMap[typeId] || 'info'
}

/**
 * 是否显示工艺路线字段
 * 只有成品和半成品才显示工艺路线选择
 */
const showProcessRoute = computed(() => {
  return form.itemTypeId === 2 || form.itemTypeId === 3 // 成品(2)或半成品(4)
})

/**
 * 新增产品物料
 * 打开新增对话框并重置表单
 */
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增'
  dialogVisible.value = true
  resetForm()
}

/**
 * 编辑产品物料
 * 打开编辑对话框并填充当前行数据
 */
const handleEdit = (row: ProductMaterial) => {
  isEdit.value = true
  dialogTitle.value = '编辑产品物料'
  dialogVisible.value = true

  Object.assign(form, {
    id: row.id,
    materialsCode: row.materialsCode,
    materialsName: row.materialsName,
    materialsMsg: row.materialsMsg,
    spec: row.spec,
    unit: row.unit, // 直接使用数字，不需要转换为字符串
    warnQty: row.warnQty,
    itemTypeId: row.itemTypeId, // 直接使用数字，不需要转换为字符串
    itemName: row.itemGroupName,
    routingId: row.routingId, // 直接使用数字，不需要转换为字符串
    addProp: row.addProp
  })
}

/**
 * 删除单个产品物料
 * 带确认提示的删除操作
 */
const handleDelete = async (row: ProductMaterial) => {
  try {
    await ElMessageBox.confirm('确定要删除这个产品物料吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsDel`, {
      Id: row.id
    })

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getProductMaterials()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 批量删除产品物料
 * 支持多选删除，带确认提示
 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的产品物料')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个产品物料吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const deletePromises = selectedRows.value.map(row =>
      Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsBatchDel`, { Ids: [row.id] })
    )

    await Promise.all(deletePromises)
    ElMessage.success('批量删除成功')
    getProductMaterials()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

/**
 * 导出产品物料数据
 * 支持条件筛选导出，生成Excel文件
 */
const handleExport = async () => {
  try {
    const requestData = {
      MaterialsCode: searchForm.materialsCode || null,
      MaterialsName: searchForm.materialsName || null,
      MaterialsMsg: searchForm.materialsMsg || null,
      Spec: searchForm.spec || null,
      ItemTypeId: searchForm.itemTypeId,
      ItemName: searchForm.itemName || null,
      Format: 'xlsx'
    }

    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsExport`, requestData, {
      responseType: 'blob'
    })

    // 创建下载链接
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `产品物料数据_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

/**
 * 导入产品物料数据
 * 直接文件选择方式，无需弹出窗口
 * 支持.xlsx和.xls格式的Excel文件
 */
const handleImport = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = async (event) => {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (!file) return

    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('overrideExisting', 'false')
      formData.append('importUser', localStorage.getItem('userNickname') || 'System')

      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsImport`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (response.data.code === 200) {
        const result = response.data.data
        ElMessage.success(`导入完成！成功：${result.successCount}条，失败：${result.failCount}条`)

        if (result.failCount > 0) {
          console.log('导入错误信息:', result.errorMessages)
          // 可以显示详细的错误信息
          ElMessage.warning(`有${result.failCount}条数据导入失败，请检查数据格式`)
        }

        // 刷新数据
        getProductMaterials()
      } else {
        ElMessage.error(response.data.message || '导入失败')
      }
    } catch (error) {
      console.error('导入失败:', error)
      ElMessage.error('导入失败，请检查文件格式')
    }
  }
  input.click()
}



// 移除不再需要的文件处理函数

/**
 * 提交表单
 * 处理新增和编辑两种模式的数据提交
 */
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    const requestData = {
      Id: form.id || 0,
      MaterialsCode: form.materialsCode,
      MaterialsName: form.materialsName,
      MaterialsMsg: form.materialsMsg || '',
      Spec: form.spec || '',
      Unit: form.unit || 0,
      WarnQty: form.warnQty,
      ItemTypeId: form.itemTypeId || 0,
      ItemName: form.itemName,
      RoutingId: showProcessRoute.value ? (form.routingId || 0) : 0,
      AddProp: localStorage.getItem('userNickname') || '',
      UpdProp: isEdit.value ? localStorage.getItem('userNickname') || '' : ''
    }

    console.log('提交数据:', requestData)

    if (isEdit.value) {
      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsUp`, requestData)
      if (response.data.code === 200) {
        ElMessage.success(response.data.message || '更新成功')
      } else {
        ElMessage.error(response.data.message || '更新失败')
        return
      }
    } else {
      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsAdd`, requestData)
      if (response.data.code === 200) {
        ElMessage.success(response.data.message || '添加成功')
      } else {
        ElMessage.error(response.data.message || '添加失败')
        return
      }
    }

    dialogVisible.value = false
    getProductMaterials()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

/**
 * 重置表单
 * 清空所有表单字段并设置默认值
 */
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: 0,
    materialsCode: '',
    materialsName: '',
    materialsMsg: '',
    spec: '',
    unit: null,
    warnQty: 0,
    itemTypeId: null,
    itemName: '',
    routingId: null,
    addProp: localStorage.getItem("userNickname") || ''
  })
}

/**
 * 物料类型变化处理
 * 当物料类型改变时，清空相关字段并重新加载依赖数据
 */
const handleItemTypeChange = () => {
  // 如果不是成品或半成品，清空工艺路线
  if (!showProcessRoute.value) {
    form.routingId = null
  }
  // 清空群组，因为群组类型变化了
  form.itemName = ''
}

/**
 * 群组名称变化处理
 * 当群组改变时，自动匹配对应的工艺路线
 */
const handleItemGroupChange = () => {
  // 如果是成品或半成品，根据群组自动反填工艺路线
  if (showProcessRoute.value && form.itemName) {
      // 根据群组名称查找对应的工艺路线
      const selectedGroup = itemGroups.value.find(group => group.itemName === form.itemName)
      if (selectedGroup) {
        // 这里可以根据群组ID或名称来匹配工艺路线
        // 暂时使用模拟逻辑，实际应该根据业务规则来匹配
        const defaultRoute = processRoutes.value.find(route =>
          route.routingName.includes(selectedGroup.itemName) ||
          selectedGroup.itemName.includes(route.routingName)
        )
        if (defaultRoute) {
          form.routingId = defaultRoute.id
        } else {
          // 如果没有找到匹配的工艺路线，使用第一个可用的
          if (processRoutes.value.length > 0) {
            form.routingId = processRoutes.value[0].id
          }
        }
      }
  } else if (!showProcessRoute.value) {
    form.routingId = null
  }
}

/**
 * 处理表格行选择变化
 * 更新选中的行数据，用于批量操作
 */
const handleSelectionChange = (selection: ProductMaterial[]) => {
  selectedRows.value = selection
}

/**
 * 处理分页大小变化
 * 当每页显示数量改变时，重新加载数据
 */
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  getProductMaterials()
}

/**
 * 处理当前页码变化
 * 当页码改变时，重新加载对应页的数据
 */
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getProductMaterials()
}

/**
 * 执行搜索操作
 * 根据搜索条件筛选数据并保存搜索历史
 */
const handleSearch = () => {
  currentPage.value = 1

  if (hasSearchConditions.value) {
    const currentSearch = {
      materialsCode: searchForm.materialsCode,
      materialsName: searchForm.materialsName,
      materialsMsg: searchForm.materialsMsg,
      spec: searchForm.spec,
      itemTypeId: searchForm.itemTypeId,
      itemName: searchForm.itemName
    }

    const exists = searchHistory.value.some(item =>
      item.materialsCode === currentSearch.materialsCode &&
      item.materialsName === currentSearch.materialsName &&
      item.materialsMsg === currentSearch.materialsMsg &&
      item.spec === currentSearch.spec &&
      item.itemTypeId === currentSearch.itemTypeId &&
      item.itemName === currentSearch.itemName
    )

    if (!exists) {
      searchHistory.value.unshift(currentSearch)
      if (searchHistory.value.length > 10) {
        searchHistory.value = searchHistory.value.slice(0, 10)
      }
    }
  }

  getProductMaterials()
}

/**
 * 切换搜索区域的显示/隐藏状态
 * 支持快捷键Ctrl+F触发
 */
const toggleSearchArea = () => {
  showSearchArea.value = !showSearchArea.value
}

/**
 * 刷新数据列表
 * 重新加载当前页数据，支持F5快捷键
 */
const refreshData = () => {
  getProductMaterials()
  ElMessage.success('数据已刷新')
}

/**
 * 切换浏览器全屏模式
 * 提供更好的用户体验
 */
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

/**
 * 清空搜索条件
 * 重置所有搜索字段并重新加载数据
 */
const clearSearch = () => {
  searchForm.materialsCode = ''
  searchForm.materialsName = ''
  searchForm.materialsMsg = ''
  searchForm.spec = ''
  searchForm.itemTypeId = null
  searchForm.itemName = ''
  handleSearch()
  ElMessage.success('搜索条件已清空')
}

// ==================== 计算属性 ====================
/**
 * 检查是否有搜索条件
 * 用于控制搜索状态显示
 */
const hasSearchConditions = computed(() => {
  return searchForm.materialsCode || searchForm.materialsName || searchForm.materialsMsg ||
    searchForm.spec || searchForm.itemTypeId || searchForm.itemName
})

/**
 * 获取当前搜索条件的文本描述
 * 用于显示搜索状态标签
 */
const getSearchConditionsText = () => {
  const conditions = []
  if (searchForm.materialsCode) conditions.push(`编码: ${searchForm.materialsCode}`)
  if (searchForm.materialsName) conditions.push(`名称: ${searchForm.materialsName}`)
  if (searchForm.materialsMsg) conditions.push(`描述: ${searchForm.materialsMsg}`)
  if (searchForm.spec) conditions.push(`规格: ${searchForm.spec}`)
  if (searchForm.itemTypeId) {
    const groupType = groupTypes.value.find(type => type.id === searchForm.itemTypeId)
    conditions.push(`类型: ${groupType ? groupType.groupTypeName : '未知'}`)
  }
  if (searchForm.itemName) conditions.push(`群组: ${searchForm.itemName}`)
  return conditions.join(', ')
}

/**
 * 获取搜索历史项的文本描述
 * 用于显示搜索历史下拉菜单
 */
const getSearchHistoryText = (item: { materialsCode: string, materialsName: string, materialsMsg: string, spec: string, itemTypeId: number | null, itemName: string }) => {
  const conditions = []
  if (item.materialsCode) conditions.push(`编码: ${item.materialsCode}`)
  if (item.materialsName) conditions.push(`名称: ${item.materialsName}`)
  if (item.materialsMsg) conditions.push(`描述: ${item.materialsMsg}`)
  if (item.spec) conditions.push(`规格: ${item.spec}`)
  if (item.itemTypeId) {
    const groupType = groupTypes.value.find(type => type.id === item.itemTypeId)
    conditions.push(`类型: ${groupType ? groupType.groupTypeName : '未知'}`)
  }
  if (item.itemName) conditions.push(`群组: ${item.itemName}`)
  return conditions.join(', ') || '空搜索'
}

/**
 * 加载搜索历史记录到搜索表单
 * 从历史记录中恢复搜索条件
 */
const loadSearchHistory = (item: { materialsCode: string, materialsName: string, materialsMsg: string, spec: string, itemTypeId: number | null, itemName: string }) => {
  searchForm.materialsCode = item.materialsCode
  searchForm.materialsName = item.materialsName
  searchForm.materialsMsg = item.materialsMsg
  searchForm.spec = item.spec
  searchForm.itemTypeId = item.itemTypeId
  searchForm.itemName = item.itemName
  handleSearch()
  ElMessage.success('已加载搜索历史')
}

/**
 * 处理键盘快捷键事件
 * 支持Ctrl+F搜索切换，F5刷新等快捷键
 */
const handleKeydown = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.key === 'f') {
    event.preventDefault()
    toggleSearchArea()
  }
  if (event.key === 'F5') {
    event.preventDefault()
    refreshData()
  }
}

// ==================== 生命周期钩子 ====================
/**
 * 组件挂载时初始化
 * 加载基础数据和设置事件监听
 */
onMounted(() => {
  getGroupTypes()
  getItemGroups()
  getUnits()
  getProcessRoutes()
  getProductMaterials()

  document.addEventListener('keydown', handleKeydown)
})

/**
 * 组件卸载时清理
 * 移除事件监听器，防止内存泄漏
 */
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
/**
 * 产品物料管理页面样式
 * 包含布局、组件样式、响应式设计等
 */

/* 主容器样式 */
.product-materials-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部操作区域样式 */
.top-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 操作按钮区域样式 */
.action-section {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 搜索区域样式 */
.search-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.search-status {
  width: 100%;
  margin-bottom: 5px;
}

.search-controls {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: nowrap;
  overflow-x: auto;
}

.search-input {
  width: 150px;
  flex-shrink: 0;
}

.search-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.clear-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.history-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 操作按钮区域样式 */
.action-buttons {
  display: flex;
  gap: 10px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.delete-btn:hover {
  background-color: #f78989;
  border-color: #f78989;
}

/* 工具图标区域样式 */
.utility-icons {
  display: flex;
  gap: 15px;
}

.icon-btn {
  font-size: 18px;
  color: #606266;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.icon-btn:hover {
  color: #409eff;
  background-color: #f0f9ff;
}

.icon-btn.active {
  color: #409eff;
  background-color: #f0f9ff;
}

/* 表格区域样式 */
.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-table {
  width: 100%;
}

.search-icon {
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
}

.sort-icon {
  margin-left: 3px;
  font-size: 12px;
  color: #909399;
}

.action-link {
  color: #409eff;
  text-decoration: none;
  margin: 0 5px;
}

.delete-link {
  color: #f56c6c;
}

/* 分页区域样式 */
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-summary {
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

.pagination-controls .el-pagination {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0;
}

/* 表单样式：新增/编辑对话框中的表单样式 */
.material-form {
  padding: 20px 0;
  background-color: #fff;
}

.material-form .el-form-item {
  margin-bottom: 24px;
}

.material-form .el-form-item__label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}

.material-form .el-form-item__label.is-required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.material-form .el-input,
.material-form .el-select {
  width: 100%;
  font-size: 14px;
  line-height: 1.5;
}

.material-form .el-input-number {
  flex: 1;
  min-width: 0;
  font-size: 14px;
  line-height: 1.5;
}

.material-form .el-input-number .el-input__wrapper {
  font-size: 14px;
  line-height: 1.5;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s;
  padding: 0 8px;
  box-shadow: none;
  background-color: #fff;
  min-height: 32px;
}

.material-form .el-input-number .el-input__wrapper:hover {
  border-color: #c0c4cc;
  box-shadow: none;
}

.material-form .el-input-number .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: none;
}

.material-form .el-input-number .el-input__inner {
  border: none;
  font-size: 14px;
  line-height: 1.5;
  background: transparent;
  padding: 0;
}

.material-form .el-input-number .el-input__inner:focus {
  border: none;
  outline: none;
}

.material-form .el-input-number .el-input__inner:hover {
  border: none;
}

.material-form .el-input__inner,
.material-form .el-select .el-input__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s;
  font-size: 14px;
  line-height: 1.5;
  box-shadow: none;
  background-color: #fff;
  min-height: 32px;
}

.material-form .el-input__inner:focus,
.material-form .el-select .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: none;
}

.material-form .el-input__inner:hover,
.material-form .el-select .el-input__inner:hover {
  border-color: #c0c4cc;
  box-shadow: none;
}

.material-form .el-textarea__inner {
  resize: both;
  min-height: 80px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s;
  font-size: 14px;
  line-height: 1.5;
  box-shadow: none;
  background-color: #fff;
  padding: 8px 12px;
}

.material-form .el-textarea__inner:focus {
  border-color: #409eff;
  box-shadow: none;
}

.material-form .el-textarea__inner:hover {
  border-color: #c0c4cc;
  box-shadow: none;
}

/* 对话框样式：新增/编辑对话框的样式 */
.el-dialog {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  background-color: #f8f9fa;
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.el-dialog__body {
  padding: 24px;
  background-color: #fff;
}

.el-dialog__footer {
  background-color: #f8f9fa;
  padding: 16px 24px;
  border-top: 1px solid #e9ecef;
}

/* 按钮样式：主要按钮和通用按钮样式 */
.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 8px 20px;
  font-size: 14px;
}

/* 信息图标样式：表单中的提示图标 */
.info-icon {
  color: #909399;
  font-size: 16px;
  cursor: help;
  flex-shrink: 0;
}

.info-icon:hover {
  color: #409eff;
}

/* 搜索区域动画：搜索区域的显示/隐藏过渡效果 */
.search-slide-enter-active,
.search-slide-leave-active {
  transition: all 0.3s ease;
}

.search-slide-enter-from,
.search-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.search-slide-enter-to,
.search-slide-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 100px;
}

/* 移除导入对话框相关样式：已删除的导入对话框样式 */

/* 响应式设计：移动端适配 */
@media (max-width: 768px) {
  .top-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-controls {
    flex-wrap: wrap;
    overflow-x: visible;
  }

  .search-input {
    width: 100%;
    min-width: 120px;
  }

  .action-section {
    padding: 10px 15px;
  }

  .action-buttons {
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
  }

  .utility-icons {
    justify-content: center;
  }

  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
}
</style>
